using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers
{
    /// <summary>
    /// 医院管理控制器
    /// 提供医院的增删改接口
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class HospitalController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<HospitalController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public HospitalController(IMediator mediator, ILogger<HospitalController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建新医院
        /// </summary>
        /// <param name="createDto">医院创建信息</param>
        /// <returns>创建成功的医院信息</returns>
        [HttpPost]
        public async Task<ActionResult<APIResult<HospitalDto>>> CreateHospital([FromBody] HospitalCreateDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.SelectMany(x => x.Value?.Errors ?? Enumerable.Empty<Microsoft.AspNetCore.Mvc.ModelBinding.ModelError>())
                        .Select(x => x.ErrorMessage)
                        .ToList();
                    return BadRequest(new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join(";", errors)
                    });
                }

                _logger.LogInformation("接收到创建医院请求：{@CreateDto}", createDto);

                // 获取当前用户信息（这里简化处理，实际应该从认证信息中获取）
                var uploader = "System"; // TODO: 从认证信息中获取当前用户

                var command = new CreateHospitalCommand(createDto, uploader);
                var result = await _mediator.Send(command);

                return result.Code == APIEnum.OK ? Ok(result) : BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建医院时发生错误");
                return StatusCode(500, new APIResult<HospitalDto>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 更新医院信息
        /// </summary>
        /// <param name="updateDto">医院更新信息</param>
        /// <returns>更新成功的医院信息</returns>
        [HttpPut]
        public async Task<ActionResult<APIResult<HospitalDto>>> UpdateHospital([FromBody] HospitalUpdateDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.SelectMany(x => x.Value?.Errors ?? Enumerable.Empty<Microsoft.AspNetCore.Mvc.ModelBinding.ModelError>())
                        .Select(x => x.ErrorMessage)
                        .ToList();
                    return BadRequest(new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join(";", errors)
                    });
                }

                _logger.LogInformation("接收到更新医院请求：{@UpdateDto}", updateDto);

                var command = new UpdateHospitalCommand(updateDto);
                var result = await _mediator.Send(command);

                return result.Code == APIEnum.OK ? Ok(result) : BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新医院时发生错误");
                return StatusCode(500, new APIResult<HospitalDto>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 删除医院
        /// </summary>
        /// <param name="id">医院ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<APIResult<bool>>> DeleteHospital(int id)
        {
            try
            {
                _logger.LogInformation("接收到删除医院请求，ID：{Id}", id);

                var command = new DeleteHospitalCommand(id);
                var result = await _mediator.Send(command);

                return result.Code == APIEnum.OK ? Ok(result) : BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除医院时发生错误，ID：{Id}", id);
                return StatusCode(500, new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 批量删除医院
        /// </summary>
        /// <param name="ids">医院ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<ActionResult<APIResult<bool>>> BatchDeleteHospitals([FromBody] List<int> ids)
        {
            try
            {
                _logger.LogInformation("接收到批量删除医院请求，IDs：{@Ids}", ids);

                var command = new BatchDeleteHospitalsCommand(ids);
                var result = await _mediator.Send(command);

                return result.Code == APIEnum.OK ? Ok(result) : BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除医院时发生错误");
                return StatusCode(500, new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误"
                });
            }
        }
    }
}